# 获取当前用户目录下的所有conda环境路径
# (English: Retrieve all conda environment paths under the current user's directory)
$envs = (conda env list --json | ConvertFrom-Json).envs

# 获取当前日期时间，格式为年月日_小时分钟秒
# (English: Get the current date and time in the format of YYYYMMDD_HHMMSS)
$datetime = Get-Date -Format "yyyyMMdd_HHmmss"

# 输出文件名
# (English: Output file name)
$output_file = "conda_windows_$datetime.csv"

# 定义一个函数来获取文件夹大小，并以合适的单位显示
# (English: Define a function to get the size of the folder in a suitable unit)
function Get-FolderSize {
    param (
        [string]$path
    )
    
    # 计算文件夹大小，单位为字节
    $sizeInBytes = (Get-ChildItem -Path $path -Recurse | Measure-Object -Property Length -Sum).Sum
    
    # 转换大小为合适的单位并保留两位小数
    if ($sizeInBytes -lt 1024) {
        return "{0:N2}B" -f $sizeInBytes
    }
    elseif ($sizeInBytes -lt 1048576) {
        return "{0:N2}KB" -f ($sizeInBytes / 1024)
    }
    elseif ($sizeInBytes -lt 1073741824) {
        return "{0:N2}MB" -f ($sizeInBytes / 1048576)
    }
    elseif ($sizeInBytes -lt 1099511627776) {
        return "{0:N2}GB" -f ($sizeInBytes / 1073741824)
    }
    else {
        return "{0:N2}TB" -f ($sizeInBytes / 1099511627776)
    }
}

# 输出表头到 CSV 文件
# (English: Output the header to the CSV file)
"Environment,Size" | Out-File $output_file

# 遍历每个环境并获取其大小
# (English: Iterate through each environment and get its size)
foreach ($env in $envs) {
    $folderSize = Get-FolderSize -path $env
    # 使用 Write-Output 确保对齐，最多40个字符宽度
    Write-Output "$env`t$folderSize"
    
    # 将结果保存到 CSV 文件
    "`"$env`",`"$folderSize`"" | Out-File $output_file -Append
}

Write-Host "Results saved to $output_file"